<template>
	<div class="asset-add-ifno">
		<nav-header>
			<template slot="menuBefore">
				<li><router-link to="/affairs/asset/asset-list" tag="a">资产管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
		</nav-header>

        <el-form 
            :model="addForm" 
            :rules="rules" 
            ref="addForm" 
            label-width="150px" 
            class="add-form" 
            v-loading="loading.status" 
            :element-loading-text="loading.txt">
            <el-form-item label="资产编号">
                <el-input v-model="addForm.number" disabled></el-input>
            </el-form-item>
            <el-form-item label="资产名称" prop="name">
                <el-input v-model="addForm.name" maxlength="40" placeholder="输入资产名称，40个字以内"></el-input>
            </el-form-item>
            <el-form-item label="购买时间">
                <el-date-picker
                    v-model="addForm.buyTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择时间"
                    style="width:100%">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="资产分类" prop="classification">
                <el-select v-model="addForm.classification" placeholder="请选择资产分类" clearable>
                    <el-option :label="item.name" :value="item.id" v-for="(item, inx) in classificationList" :key="inx"></el-option>
                </el-select>
                <span class="item-btn-box" @click="addClassify">分类管理</span>
            </el-form-item>
            <el-form-item label="信息（品牌-型号）">
                <el-input v-model="addForm.info" placeholder="填入品牌跟型号；如康佳XR01"></el-input>
            </el-form-item>
            <el-form-item label="数量" prop="count">
                <el-input-number 
                    class="input-number-text"
                    v-model="addForm.count" 
                    controls-position="right" 
                    :min="1" 
                    :max="9999"
                    :precision="0"
                    :maxLength="4"
                    @change="setPrice($event, 'num')"
                    placeholder="选择资产数量">
                </el-input-number>
            </el-form-item>
            <el-form-item label="单位">
                <el-input v-model="addForm.unit" placeholder="填入资产单位，如：台"></el-input>
            </el-form-item>
            <el-form-item label="单件价格（元）">
                <el-input-number 
                    class="input-number-text"
                    v-model="addForm.price" 
                    controls-position="right" 
                    :min="0" 
                    :precision="2"
                    @change="setPrice"
                    placeholder="填入单件价格，不能为0">
                </el-input-number>
            </el-form-item>
            <el-form-item label="总购入价格（元）">
                <el-input v-model="addForm.total" placeholder="总购入价格=单件价格*数量" disabled></el-input>
            </el-form-item>
            <el-form-item label="存放点">
                <el-input v-model="addForm.place" placeholder="填入资产存放地点：如总务库房"></el-input>
            </el-form-item>
            <el-form-item label="归属">
                <el-input v-model="addForm.belong" placeholder="填入资产归属部门/班级/人"></el-input>
            </el-form-item>
            <el-form-item label="保管人">
                <el-input v-model="addForm.bailee" placeholder="填入资产归属部门/班级/人"></el-input>
            </el-form-item>
            <!-- <el-form-item label="保管人联系方式">
                <el-input v-model.number="addForm.phone" maxLength="11" placeholder="填入保管人联系方式"></el-input>
            </el-form-item> -->
            <el-form-item label="保管人联系电话" prop="phone">
                <el-input 
                    v-model="addForm.phone" 
                    placeholder="填入保管人联系电话" 
                    :maxlength="11">
                </el-input>
			</el-form-item>
            <el-form-item label="资产状态" prop="assetState">
                <el-input v-model="addForm.assetState" disabled></el-input>
                <span class="item-btn-box" @click="editState">编辑状态</span>
            </el-form-item>
            <el-form-item label="固定资产图片">
                <uploader 
                    :options="uploadOptions" 
                    :autoStart="true" 
                    ref="uploader" 
                    :file-status-text="statusText"
                    @files-submitted="fileSubmit"
                    @file-removed="fileRemoved" 
                    @file-success="fileSuccess" 
                    @file-error="fileFail"  
                    class="uploader-example">
                        <uploader-unsupport></uploader-unsupport>
                        <uploader-btn :directory="false" :attrs="attrs" :single="true">选择图片</uploader-btn>
                </uploader>

                <span v-if="!addForm.picture.file_name">未选择文件</span>
                <span v-else class="preview-asset-img">
                    <img :src="BASE_URL + addForm.picture.file_path" @click="checkImg" />{{addForm.picture.file_name}}
                </span>
            </el-form-item>
            <el-form-item label="备注">
                <el-input
                    type="textarea"
                    placeholder="在此输入备注"
                    :rows="4"
                    v-model="addForm.remark"
                    maxlength="140"
                    show-word-limit>
                </el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="resetForm" plain>取消</el-button>
                <el-button type="primary" @click="submitForm('addForm')">保存</el-button>
            </el-form-item>
        </el-form>

        <el-dialog 
            title="分类管理" 
            :visible.sync="classVisible" 
            class="add-classify-manage" 
            width="550px" 
            :before-close="cancelClass"
            :close-on-click-modal="false">
            <div>
                <span>添加分类：</span>
                <el-input 
                    style="width: 377px;margin-left: 30px;"
                    v-model.trim="classify" 
                    @blur="addClassifyWords"
                    :maxLength="10"
                    clearable
                    @keyup.enter.native.stop="$event.target.blur"
                    placeholder="10个字符内">
                 </el-input>
            </div>
            <div class="text-box">
                <span v-for="(item, inx) in classifyList" :key="inx">
                    {{item.name}}<i class="el-icon-close" @click="deleteClassify(inx)"></i>
                </span>
            </div>
            <div>
                <i class="el-icon-info"></i>
                <span>删除已创建分类将会使得原绑定该分类的资产无绑定分类</span>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelClass" plain>取消</el-button>
                <el-button type="primary" @click="addClass">确定</el-button>
            </div>
        </el-dialog>

        <el-dialog 
            title="编辑状态" 
            :visible.sync="stateVisible" 
            class="add-state-manage" 
            width="400px" 
            :before-close="cancelState"
            :close-on-click-modal="false">
            <div>
                <span>数量：</span>
                <span>{{addForm.count}}</span>
            </div>
            <div>
                <span>状态：</span>
                <div>
                    <div v-for="(item, inx) in tempStateList" :key="inx">
                        <el-select v-model="item.num" @change="setStateNum($event, inx)" placeholder="请选择数量" filterable>
                            <el-option
                                v-for="(item1, inx1) in parseInt(item.num ? item.num : 0)"
                                :key="inx1"
                                :label="item1"
                                :value="item1">
                            </el-option>
                        </el-select>
                        <el-select v-model="item.name" @change="setStateName($event, inx)" placeholder="请选择状态" filterable>
                            <el-option
                                v-for="(item2, inx2) in stateList"
                                :key="inx2"
                                :label="item2"
                                :value="item2">
                            </el-option>
                        </el-select>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="cancelState" plain>取消</el-button>
                <el-button type="primary" @click="submitState">确定</el-button>
            </div>
        </el-dialog>

        <image-viewer
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
    </div>
</template>

<script>
import {uploaderFileFail} from './../../../tools/tool';

export default {
    data() {
        return {
            imagePreview: {
                showViewer: false,
                previewSrcList: []
            },
            imgVisible: false, // 图片预览
            classVisible: false, // 分类管理弹框
            stateVisible: false, // 资产编辑状态
            selectFileShow: true,//是否显示选择文件按钮
            uploadRetryTimes: 100,//文件最大重传次数
            classify: null, // 添加分类
            previewImgURL: null, // 图片预览
            defaultClassifyList: [], // 默认分类管理
            classifyList: [], // 添加分类
            classificationList: [], // 分类管理
            imageType: ['image/jpeg', 'image/bmp', 'image/png'], // 上传图片格式
            stateList: ['未使用', '使用中', '损坏', '丢失', '报废'], // 资产状态列表
            tempStateList: [], // 编辑状态中间数组
            loading: { // 数据加载状态
                status: false,
                txt: '获取数据...'
            },
            addForm: {
                number: '',
                name: '',
                buyTime: null,
                classification: null,
                info: undefined,
                count: undefined,
                unit: '',
                price: undefined,
                total: '',
                place: '',
                belong: '',
                bailee: '',
                phone: '',
                state: [],
                picture: {
                    file_size: 0,
                    file_name: '',
                    file_path: '',
                    post_fix: ''
                },
                remark: '',
                assetState: ''
            },
            attrs: {
                accept: ['image/*']
            },
            statusText: {
                success: '上传成功',  
                error: '上传出错',  
                uploading: '正在上传...',  
                paused: '暂停',  
                waiting: '等待上传'  
            },
            uploadOptions: {
                target: this.BASE_URL+'/api/resource/res_upload',
                testChunks: false,
                headers: {Authorization: `Bearer ` + this.$g.access_token},
            },
            rules: {
                name: [
                    { required: true, message: '请输入资产名称', trigger: 'blur' },
                    { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' }
                ],
                assetState: [
                    { required: true, message: '请输入资产状态', trigger: ['blur', 'change'] },
                ],
                count: [
                    { required: true, message: '请输入数量', trigger: 'blur' },
                ],
                phone: [
                    { pattern:this.rules.mobile.reg,message: '联系电话格式不正确'}
                ]
            }
        }
    },
    created() {
        this.getNumber();
        this.getClassification();
    },
    computed: {
        imageIndex() {
            return 0;
        }
    },
    methods: {
        /**
         * 查看图片
         * @param {Object} obj 记录信息
         */
        checkImg(obj) {
            this.imagePreview.showViewer = true;
            this.imagePreview.previewSrcList = [this.BASE_URL + this.addForm.picture.file_path];
        },
        closeViewer() {
            this.imagePreview.showViewer = false;
        },
        /**
         * 获取资产编号
         */
        getNumber() {
            this.loading.status = true;
            this.loading.txt = '正在生产资产编号';

            let success = (res => {
                this.loading.status = false;
                this.addForm.number = res.data;
            })

            this.$ajax.get('api/property/identifier', {func: {success: success}})
        },
        /**
         * 设置状态重复操作
         * @param {Number} val 下拉框选中的值
         * @param {Number} index 数组下标
         */
        setStateName(val, inx) {
            let _flag = false;
            
            this.tempStateList.forEach((item, index) => {
                if (index != inx && item.name === val) {
                    item.num += this.tempStateList[inx].num;
                    _flag = true;
                }
            })

            _flag && this.tempStateList.splice(inx, 1);
        },
        /**
         * 设置状态数量
         * @param {Number} val 下拉框选中的值
         * @param {Number} index 数组下标
         */
        setStateNum(val, index) {
            if (this.tempStateList.length > 1) {
                let number = 0;

                this.tempStateList.forEach(item => {
                    number += item.num;
                })

                if (number < this.addForm.count) {
                    this.tempStateList.push({
                        name: '',
                        num: this.addForm.count - number
                    })
                }
            } else {
                if (val != this.addForm.count) {
                    this.tempStateList.push({
                        name: '',
                        num: this.addForm.count - val
                    })
                }
            }
        },
        /**
         * 获取资产状态
         */
        getState() {
            let name = '';
            this.addForm.state.forEach((item, inx) => {
                name += (inx === 0 ? '' : '; ') + item.name + '(' + item.num + ')';
            })

            this.addForm.assetState = name;
        },
        /**
         * 提交编辑状态
         */
        submitState() {
            for (let i=0; i<this.tempStateList.length; i++) {
                if (this.tempStateList[i].name === '') {
                    this.$message.warning('请选择状态！');
                    return false;
                }
            }

            this.stateVisible = false;
            this.addForm.state = deep_clone(this.tempStateList);
            this.getState();
        },
        /**
         * 编辑资产状态
         */
        editState() {
            if (!this.addForm.count) {
                this.$message.warning('请填写数量');
                return false;
            }

            if (this.addForm.state.length === 0) {
                this.addForm.state.push({
                    num: this.addForm.count,
                    name: ''
                })
            }

            let count = 0;

            this.addForm.state.forEach(item => {
                count += item.num;
            })

            if (this.addForm.count > count) {
                let _inx;
                let _flag = false;

                this.addForm.state.forEach((item, index) => {
                    if (item.name === '' && !_flag) {
                        _flag = true;
                        _inx = index;
                    }
                })

                if (_flag) {
                    this.addForm.state[_inx].num += this.addForm.count - count;
                } else {
                    this.addForm.state.push({
                    num: this.addForm.count - count,
                    name: ''
                })
                }
            } else if (this.addForm.count < count) {
                this.$message.error('数量不足，已重置资产状态！');
                
                

                this.addForm.state.push({
                    num: this.addForm.count,
                    name: ''
                })
            }

            this.tempStateList = deep_clone(this.addForm.state);
            this.stateVisible = true;
        },
        /**
         * 取消编辑状态
         */
        cancelState() {
            this.stateVisible = false;
        },
        /**
         * 弹出分类管理框
         */
        addClassify() {
            this.classify = '';
            this.classifyList = deep_clone(this.defaultClassifyList);
             this.classVisible = true;
        },
        /**
         * 添加分类
         */
        addClassifyWords() {
            if (this.classify === '') {
                return false;
            }

            for (let i=0,len=this.classifyList.length; i<len; i++) {
                if (this.classifyList[i].name === this.classify) {
                    this.$message.error('不可以添加重名的分类');
                    return false;
                }
            }

            this.classifyList.push({
                name: this.classify
            })

            this.classify = '';
        },
        /**
         * 删除分类
         * @param {Number} inx 数组下标
         */
        deleteClassify(inx) {
            this.classifyList.splice(inx, 1);
        },
        /**
         * 添加资产分类管理
         */
        addClass() {
            const success = (res => {
                this.$message.success(res.msg);
                this.classVisible = false;

                this.getClassification();
            })

            this.$ajax.post("api/property/type", this.classifyList, {func: {success: success}});
        },
        /**
         * 取消分类管理
         */
        cancelClass() {
            this.classVisible = false;
        },
         /**
         * 获取分类管理
         */
        getClassification() {
            let success = (res => {
                this.classificationList = deep_clone(res.data);
                this.defaultClassifyList = deep_clone(res.data);
            })

            this.$ajax.get('api/property/type', {func: {success: success}})
        },
        /**
         * 自动生产总价格
         * @param {String} val 输入框数值
         * @param {String} flag 数量标识
         */
        setPrice(val, flag) {
            if (this.addForm.count && this.addForm.price) {
                this.addForm.total = this.addForm.count * this.addForm.price;
            } else {
                this.addForm.total = '';
            }

            if (flag === 'num') {
                this.addForm.assetState = '';
                this.addForm.state = [];
            }
        },
        /**
         * 保存资产
         * @param {String} formName 表单 ref
         */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading.status = true;

                    let spread = [];
                    let statusList = ['未使用', '使用中', '损坏', '丢失', '报废'];
                    this.addForm.state.forEach(item => {
                        spread.push({
                            status: statusList.indexOf(statusList.filter(val => item.name === val).join()) + 1 + '',
                            number: item.num + ''
                        })
                    })

                    let params = {
                        identifier: this.addForm.number,
                        type_id: this.addForm.classification,
                        name: this.addForm.name,
                        brand: (this.addForm.info !== '' || this.addForm.info !== undefined) ? this.addForm.info : undefined,
                        number: this.addForm.count,
                        unit: this.addForm.unit,
                        price: this.addForm.price === undefined ? 0 : this.addForm.price,
                        place: this.addForm.place,
                        owner: this.addForm.belong,
                        manager: this.addForm.bailee,
                        mobile: this.addForm.phone,
                        thumb: this.addForm.picture.file_path,
                        comment: this.addForm.remark,
                        spread: spread,
                        buy_time: this.addForm.buyTime 
                    }

                    const success = (res => {
                        this.$message.success(res.msg);
                        this.$router.push('/affairs/asset/asset-list');

                    })
                    const fail = (res => {
                        this.$message.error(res.msg);
                        this.loading.status = false;
                    })

                    this.$ajax.post("api/property/single", params, {func: {success: success, fail: fail}});
                } else {
                    return false;
                }
            });
        },
        /**
         * 取消添加资产
         */
        resetForm() {
            this.$router.push('/affairs/asset/asset-list');
        },
        /**
         * 过滤文件格式
         */
        fileSubmit(files, fileList, event){
            for (let i=0; i<fileList.length; i++) {
                let file_type = fileList[i].fileType.toLocaleLowerCase();

                if(!this.imageType.includes(file_type)){
                    this.$message.warning('只允许上传 bmp/jpg/jpeg/png 格式图片');
                    this.$refs.uploader.uploader.removeFile(fileList[i]);

                    return false;
                } else if (fileList[i].size > 10240000) {
                    this.$message.warning("只允许上传10M以内的文件");
                    this.$refs.uploader.uploader.removeFile(fileList[i]);
                    return false;
                } else {
                    if(this.$refs.uploader.uploader.fileList.length > 1){
                        //删除第一张图片
                        this.$refs.uploader.uploader.removeFile(this.$refs.uploader.uploader.fileList[0]);
                    }

                    this.previewImgURL = window.URL.createObjectURL(fileList[i].file);
                    this.addForm.picture.file_size = fileList[i].size;
                    this.selectFileShow = false;
                }
            }
        },
        /**
         * 上传成功回调
         */
        fileSuccess (rootFile, file, message, chunk) { 
            let mess = eval('(' + message + ')');
            mess = handleResponseData( mess );

            if(parseInt(mess.data.status) === 1 ){
                this.addForm.picture.file_name = mess.data.file_name;
                this.addForm.picture.file_path = mess.data.file_path;
                this.addForm.picture.post_fix = mess.data.post_fix;
                this.previewImgURL = mess.data.file_path;
            }
        },
        /**
         * 上传失败回调
         */
        fileFail(rootFile, file, message, chunk) {
            uploaderFileFail(this, this.$refs.uploader.uploader, file, message);
        },
        /**
         * 移除文件
         */
        fileRemoved(file){
            this.selectFileShow = true;
            this.previewImgURL = '';
        },
    },
}
</script>

<style lang="scss">
    .asset-add-ifno {
        .add-form {
            .el-form-item > .el-form-item__content {
                max-width: 600px;
            }
        }

        .preview-asset-img {
            img {
                margin-top: -3px;
                margin-right: 11px;
                width: 32px;
                height: 32px;
                object-fit: cover;
                vertical-align: middle;
                cursor: pointer;
            }
        }

        .uploader-example {
            display: inline-block;
            
            >span {
                margin-right: 20px;
                padding: 5px 30px;
                font-size: 14px;
                color: #348EFC;
                border: 1px solid #348EFC;
                border-radius: 4px;
            }
        }

        .uploader-example + span {
            font-size: 12px;
            color: #999999;
        }

        .input-number-text {
            width: 100%;

            >span {
                display: none;
            }

            input {
                text-align: left;
            }
        }

        .item-btn-box {
            position: absolute;
            bottom: 0;
            right: -80px;
            color: #348EFC;
            cursor: pointer;
        }

        .asset-state {
            >label::before {
                content: '*';
                color: #f56c6c;
                margin-right: 4px;
            }
        }

        .add-classify-manage {
            .el-dialog__body {
                >div:last-child {
                    font-size: 12px;
                    color: #666666;
                }

                .text-box {
                    margin: 20px 0 10px 0;
                    padding: 10px;
                    min-height: 160px;
                    background: #F6F6F6;
                    border: 1px solid #DDDDDD;

                    span {
                        display: inline-block;
                        margin-right: 6px;
                        margin-bottom: 6px;
                        padding: 0 10px;
                        line-height: 36px;
                        height: 36px;
                        font-size: 14px;
                        color: #000000;
                        background: #FFFFFF;
                        border-radius: 4px;
                        border: 1px solid #DDDDDD;
                        box-sizing: border-box;

                        .el-icon-close {
                            margin-left: 10px;
                            color: #999999;
                        }
                    }
                }
            }
        }

        .add-state-manage {
            .el-dialog__body {
                padding: 35px 45px 0 ;

                >div {
                    margin-bottom: 15px;

                    >span:first-child {
                        display: inline-block;
                        width: 53px;
                    }

                    >div>div {
                        display: inline-block;
                        margin-bottom: 10px;

                        >div {
                            width: 120px;
                        }
                    }
                }

                >div:last-child {
                    display: flex;

                    >div {
                        flex: 1;
                    }
                }
            }
        }
    }
</style>
